package com.license.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.hp.hpl.jena.tdb.sys.Session;
import com.license.common.util.Constants;
import com.license.logic.alimentation.Food;
import com.license.logic.classification.NaiveBayesClassifier;
import com.license.logic.history.GeneticalHistory;
import com.license.logic.history.MedicalHistory;
import com.license.logic.pojo.Employee;
import com.license.logic.pojo.SmallEmployee;
import com.license.logic.preference.Activity;
import com.license.logic.preference.Preferences;
import com.license.logic.profile.EmployeeProfile;
import com.license.logic.profile.MedicalProfile;
import com.license.logic.profile.PersonalProfile;
import com.license.presentation.employee.EmployeePresentation;
import com.license.presentation.ontology.OntologyPresentation;

public class EmployeeServlet extends HttpServlet {
	
	private OntologyPresentation ontologyPresentation ;
	
	private EmployeePresentation employeePresentation;
	private NaiveBayesClassifier clasiffier;
	
	public EmployeeServlet() {
		
		ontologyPresentation = new OntologyPresentation();
		employeePresentation = new EmployeePresentation();
		clasiffier = new NaiveBayesClassifier();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		String operation = request.getParameter("operation");
		
		System.out.println("test");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String operation = request.getParameter("operation");
		String path = "";
		
		if ("createEmployee".equals(operation)){
			
			EmployeeProfile employeeProfile = getEmployeeProfile(request);
			insertEmployee(employeeProfile);
			try {
				clasiffier.clasiffy(employeeProfile.getPersonalProfile().getName());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			path = "../faces/JSFfiles/EmployeePage.jsp";
		} else if ("deleteEmployee".equals(operation)){
			String fileName = request.getParameter("userName") + Constants.XML_EXTENSION;
			fileName = Constants.EXTERN_FILE_PATH_UNCLASSIFIED + fileName;
			System.out.println("fileName: " + fileName);
			this.deleteEmployee(fileName);
			path = "../faces/JSFfiles/EmployeePage.jsp";
		} else if ("changeToEditEmployeePage".equals(operation)){
			String employeeName = request.getParameter("userName");
			EmployeeProfile employeeProfile;
			try {
				employeeProfile = selectEmployee(employeeName);
				request.getSession().setAttribute("employeeProfileToEdit", employeeProfile);
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("updateEmployee".equals(operation)){
			EmployeeProfile employeeProfile = getEmployeeProfile(request);
			String fileName = request.getParameter("userName") + Constants.XML_EXTENSION;
			fileName = Constants.EXTERN_FILE_PATH_UNCLASSIFIED + fileName;
			System.out.println("fileName: " + fileName);
			this.deleteEmployee(fileName);
			
			this.insertEmployee(employeeProfile);
			
			path = "../faces/JSFfiles/EmployeePage.jsp";
		} else if ("employeePagination".equals(operation)){
			HttpSession session = request.getSession();
			String operationType = request.getParameter("operationType");
			int pageNumber= 0;
			if (request.getParameter("pageNumber") != null){
				pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
			}
			
			int allEmployeeNumber = this.employeePresentation.countAllEmployee(Constants.EXTERN_FILE_PATH_UNCLASSIFIED);
			if("first".equals(operationType)) {
				pageNumber = 0;
			} else if ("last".equals(operationType)){
				pageNumber = allEmployeeNumber/Constants.EMPLOYEE_PAGINATION_NUMBER;
			} else if("prev".equals(operationType)){
				if (pageNumber <= 0){
					pageNumber = 0;
				} else {
					pageNumber --;
				}
			} else if ("next".equals(operationType)){
				if (pageNumber >= allEmployeeNumber/Constants.EMPLOYEE_PAGINATION_NUMBER){
					pageNumber = allEmployeeNumber/Constants.EMPLOYEE_PAGINATION_NUMBER;
				} else {
					pageNumber ++;
				}
			} else {
				pageNumber = 0;
			}
			
			session.setAttribute("pageNumber", pageNumber);
			
			path = "../faces/JSFfiles/EmployeePage.jsp";
		}
		
		try {
			if (!"".equals(path)){
				response.sendRedirect(path);
			}
			} catch (Exception e){
				
			}
			return;
	}
	
	private void deleteEmployee(String employeeFile) {
		try {
			this.employeePresentation.deleteEmployee(employeeFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	private EmployeeProfile selectEmployee(String userName) throws ParserConfigurationException, SAXException, IOException{
		String path = Constants.EXTERN_FILE_PATH_UNCLASSIFIED + userName + Constants.XML_EXTENSION;
		return employeePresentation.selectEmployee(path);
	}
	
	private EmployeeProfile getEmployeeProfile(HttpServletRequest request){
		EmployeeProfile employeeProfile = new EmployeeProfile();
		// personal profile
		PersonalProfile personalProfile = new PersonalProfile();
		personalProfile.setName(request.getParameter("name"));
		personalProfile.setWeight(Double.parseDouble(request.getParameter("weight")));
		personalProfile.setHeight(Double.parseDouble(request.getParameter("height")));
		personalProfile.setSex(request.getParameter("sex"));
		personalProfile.setAge(Integer.parseInt(request.getParameter("ageEmployee")));
		
		// set medical profile values
		MedicalProfile medicalProfile = new MedicalProfile();
		
		MedicalHistory medicalHistory = new MedicalHistory();
		medicalHistory.setDiabets(Boolean.getBoolean(request.getParameter("diabetic")));
		medicalHistory.setSbp(Integer.parseInt(request.getParameter("sbp")));
		medicalHistory.setSmoker(Boolean.getBoolean(request.getParameter("smoker")));
		
		medicalHistory.setActivityKalory(Double.parseDouble(request.getParameter("activityCalory")));
		medicalHistory.setNutritionKalory(Double.parseDouble(request.getParameter("nutritionCalory")));
		
		medicalProfile.setMedicalHistory(medicalHistory);
		
		GeneticalHistory geneticalHistory = new GeneticalHistory();
		geneticalHistory.setFamilyCardioHistory(Boolean.getBoolean(request.getParameter("familyHistory")));
		
		medicalProfile.setGeneticalHistory(geneticalHistory);
		
		employeeProfile.setMedicalProfile(medicalProfile);
		
		// set preferencies
		Preferences preferences = new Preferences();
		
		List<Food> preferencedFood = new ArrayList<Food>();
		List<Activity> preferencedActivity = new ArrayList<Activity>();
		
		for (Object str : request.getParameterMap().keySet()){
			String keyValue = str.toString();
			if(keyValue.contains("food_")){
				Food food = new Food();
				food.setName(request.getParameter(keyValue));
				preferencedFood.add(food);
			} else if (keyValue.contains("activity_")){
				Activity activity = new Activity();
				activity.setName(request.getParameter(keyValue));
				preferencedActivity.add(activity);
			}
		}
		
		preferences.setNutritions(preferencedFood);
		preferences.setActivities(preferencedActivity);
		personalProfile.setPreference(preferences);
		
		employeeProfile.setPersonalProfile(personalProfile);
		
		return employeeProfile;
	}
	
	private void insertEmployee(EmployeeProfile employeeProfile){
		try {
			this.employeePresentation.createEmployee(employeeProfile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public List<SmallEmployee> getAllSmallEmployees(){
		return this.employeePresentation.getAllSmallEmployees(Constants.EXTERN_FILE_PATH_UNHEALTY_BEHAVIOR);
	}
	
	public List<SmallEmployee> getSmallEmployees(int pageNumber){
		return this.employeePresentation.getSmallEmployees(Constants.EXTERN_FILE_PATH_UNCLASSIFIED, pageNumber);
	}
	
	public List<Employee> getEmployee(HttpServletRequest request, HttpServletResponse response) {
		List<Employee> employees = new ArrayList<Employee>();
		
		return employees;
	}
	
	public Map<String,List<String>> getEmployeePreferences(HttpServletRequest request, HttpServletResponse response) {
		Map<String,List<String>> preferences = new HashMap<String,List<String>>();
		List<String> meal = ontologyPresentation.getIndividualsFromOntClassByName(Constants.MEAL);
		List<String> soup = ontologyPresentation.getIndividualsFromOntClassByName(Constants.SOUP);
		List<String> fruit = ontologyPresentation.getIndividualsFromOntClassByName(Constants.FRUIT);
		List<String> vegetable = ontologyPresentation.getIndividualsFromOntClassByName(Constants.VEGETABLE);
		List<String> graminea = ontologyPresentation.getIndividualsFromOntClassByName(Constants.GRAMINEA);
		List<String> phisicalActivities = ontologyPresentation.getIndividualsFromOntClassByName(Constants.PREFFERED_PHISICAL_ACT); 

		List<String> auxMeal = new ArrayList<String>();
		List<String> auxSoup = new ArrayList<String>();
		List<String> auxFruit = new ArrayList<String>();
		List<String> auxVegetable = new ArrayList<String>();
		List<String> auxGraminea = new ArrayList<String>();
		List<String> auxPhiscalActivities = new ArrayList<String>();
		
		for(String preference : meal) {
			String auxPreference = preference.replaceAll("_", " ");	
			auxMeal.add(auxPreference);
		}
		
		for(String preference : soup) {
			String auxPreference = preference.replaceAll("_", " ");	
			auxSoup.add(auxPreference);
		}
		
		for(String preference : fruit) {
			String auxPreference = preference.replaceAll("_", " ");	
			auxFruit.add(auxPreference);
		}
		
		for(String preference : vegetable) {
			String auxPreference = preference.replaceAll("_", " ");	
			auxVegetable.add(auxPreference);
		}
		
		for(String preference : graminea) {
			String auxPreference = preference.replaceAll("_", " ");	
			auxGraminea.add(auxPreference);
		}
		
		for(String preference : phisicalActivities) {
			String auxPreference = preference.replaceAll("_", " ");	
			auxPhiscalActivities.add(auxPreference);
		}
		
		
		preferences.put("meal", auxMeal);
		preferences.put("soup", auxSoup);
		preferences.put("fruit", auxFruit);
		preferences.put("vegetable", auxVegetable);
		preferences.put("graminea", auxGraminea);
		preferences.put("PhisicalActivity",auxPhiscalActivities);
		
		return preferences;
	}
}
